package your_car_status

import groovy.grape.Grape
 
//@GrabResolver(name='itextpdf', root='http://maven.itextpdf.com/')


import org.springframework.dao.DataIntegrityViolationException
//para crear el archivo
import java.io.FileOutputStream
import java.io.IOException
import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
//librería itextpdf para crear el documento PDF
import com.itextpdf.text.pdf.*
import com.itextpdf.text.Document
import com.itextpdf.text.PageSize
import com.itextpdf.text.DocumentException
import com.itextpdf.text.Paragraph
import com.itextpdf.text.Font
import com.itextpdf.text.Image
import com.itextpdf.text.Phrase
import com.itextpdf.text.Chunk
import com.itextpdf.text.Element;
//import com.itextpdf.text.pdf.PdfWrite

class BillController {
   
    def pdf(Long id){
        def s = Services.get(id);  
        
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Document doc=new Document(PageSize.A4,30,30,30,30);
            def writer = PdfWriter.getInstance(doc, baos);
            doc.open();
            //doc.add(new Paragraph("Nombre:${params.nombre} , Dirección:${params.direccion}"));
            Image image = Image.getInstance(g.resource(dir: 'images', file: 'logoYCS_bill.png', absolute: true).toString());            
            image.setAlignment(Chunk.ALIGN_RIGHT);
            doc.add(image);
            
            doc.add(new Paragraph("License Plate: "+s.vehicle.licensePlate));
            doc.add(new Paragraph("Customer: "+s.vehicle.customer.name));
            doc.add(new Paragraph("Repair Shop: "+s.vehicle.customer.repairShop.name));
            doc.add(new Paragraph("Service #: "+id));
            doc.add(new Paragraph("NIT #: "+s.vehicle.customer.repairShop.id));
                                      
            doc.add(new Paragraph(" "));
            PdfPTable table = new PdfPTable(2)
            def addToTable={
                data->
                String name=data.replace("price","").replace("prince","").replaceAll("(\\p{Ll})(\\p{Lu})","\$1 \$2");
                def val=s[data]
                if (val.class==Double){
                    if(val>0){
                        table.addCell(new Paragraph(name))
                        table.addCell(new Paragraph(val.toString()))
                    }
                }
            }
            table.getDefaultCell()
            Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            
            table.addCell(new Paragraph("Service", boldFont))
            table.addCell(new Paragraph("Price", boldFont))
            //your_car_status.Services..getProperties().toString();
            def d = new DefaultGrailsDomainClass(Services.class)
            d.persistentProperties.each {addToTable(it.name)}
            doc.add(table);
            //doc.add(new Paragraph("Maximo Tiempo: ${params.max.toString()} , Total: ${params.Total.toString()}"))
            
            doc.add(new Paragraph(" "));
            Paragraph parrafo = new Paragraph("TOTAL : "+ s.total(), boldFont)
            parrafo.setAlignment(Element.ALIGN_RIGHT);
            doc.add(parrafo)
           
            
            //Barcode                
            doc.add(new Paragraph(" "));
            doc.add(new Paragraph(" ")); 
            PdfContentByte cb = writer.getDirectContent(); 
            BarcodeEAN codeEAN = new BarcodeEAN();
                        
            //BarcodeEAN 
            codeEAN.setCodeType(codeEAN.EAN13); 
            String sid=id.toString();
            for(int i=sid.length();i<13;i++){
                sid="0"+sid;
            }
            codeEAN.setCode(sid); //13 
            Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
            def phra=new Phrase(new Chunk(imageEAN, 450, 0));
            doc.add(phra);
            
            doc.close();
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close()
            
        } catch (Exception ex) {
            println(ex);
        }
        
    }
}
